package com.cote.douhahou.pretloan.launcher;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.cote.douhahou.pretloan.any.event.AkomapalendIAnalyticsEvent;
import com.cote.douhahou.pretloan.any.util.AkomapalendAnalyticsUtil;
import com.cote.douhahou.pretloan.beans.AppAkomapalendConfigCustomize;
import com.cote.douhahou.pretloan.beans.LogAkomapalendinInfo;
import com.cote.douhahou.pretloan.beans.OtheAkomapalendrsInfo;
import com.cote.douhahou.pretloan.home.HomeActivity;
import com.cote.douhahou.pretloan.network.HttpHelper;
import com.cote.douhahou.pretloan.service.CusServiceAkomapalendDialog;
import com.cote.douhahou.pretloan.utils.AkomapaLendConfigs;
import com.cote.douhahou.pretloan.utils.AkomapaLendUtil;
import com.cote.douhahou.pretloan.utils.KindTipAkomapalendDialog;
import com.cote.douhahou.pretloan.R;

import org.json.JSONException;
import org.json.JSONObject;


public class LoginActivity extends AppCompatActivity {

    private ImageButton csImageButton;
    private TextView mobileCodeTextView;
    private EditText mobileInputEditText;
    private EditText mobileCodeInputEditText;
    private Button requestCodeButton;
    private View loginButton;
    private ImageButton agreementImageButton;
    private TextView agreementTextView;
    private ImageView loginImageView;

    private boolean flag = true;

    private final View.OnClickListener requestCodeC = v -> {

        String mobile = mobileInputEditText.getText().toString().trim();

        HttpHelper.inst().submitEvent("LOGIN","SEND_CODE_CLICK",mobile);

        if (TextUtils.isEmpty(mobile)){
            Toast.makeText(this,getString(R.string.tips_enter_mobile_akomapalend),Toast.LENGTH_SHORT).show();
            return;
        }

        HttpHelper.inst().fSmsCode(this,mobile,this::requestCodeSuccess);
    };

    private final View.OnClickListener loginC = v -> {

        String mob_akomapalendile = mobileInputEditText.getText().toString().trim();
        String vercode = mobileCodeInputEditText.getText().toString().trim();

        HttpHelper.inst().submitEvent("LOGIN","CONFIRM_CLICK",mob_akomapalendile);

        if (!flag){
            new KindTipAkomapalendDialog(
                    this,
                    getString(R.string.kind_tips_privacy_policy_uncheck),
                    "",
                    getString(R.string.kind_tips_btn_agree_and_continue),
                    null,
                    () -> setFlag(true)
            ).show();
            return;
        }

        if (TextUtils.isEmpty(mob_akomapalendile)){
            Toast.makeText(this,getString(R.string.tips_enter_mobile_akomapalend),Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(vercode)){
            Toast.makeText(this,getString(R.string.tips_enter_vercode_akomapalend),Toast.LENGTH_SHORT).show();
            return;
        }

        if (AppAkomapalendConfigCustomize.instance().isTestAccount_akomapalend(mob_akomapalendile)){
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("token", AppAkomapalendConfigCustomize.instance().getTestToken_akomapalend(mob_akomapalendile));
                jsonObject.put("userId", mob_akomapalendile);
                jsonObject.put("type", AkomapaLendConfigs.LoginTypeOld);
                jsonObject.put("isAdSource","NO");
                LogAkomapalendinInfo.par_akomapalendse(jsonObject);
                loginSuccess();
            }catch (JSONException e){
                e.printStackTrace();
            }
            return;
        }

        HttpHelper.inst().lgWCode(this,mob_akomapalendile,vercode,this::loginSuccess);

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);

        csImageButton = findViewById(R.id.ala_ib_customerservice);
        mobileCodeTextView = findViewById(R.id.ala_tv_areacode);
        mobileInputEditText = findViewById(R.id.ala_et_mobile);
        mobileCodeInputEditText = findViewById(R.id.ala_et_vercode);
        requestCodeButton = findViewById(R.id.ala_btn_getcode);
        loginButton = findViewById(R.id.ala_btn_login);
        agreementImageButton = findViewById(R.id.ala_ib_agreement);
        agreementTextView = findViewById(R.id.ala_tv_privacypolicy);
        loginImageView = findViewById(R.id.ala_iv_login);

        mobileInputEditText.setInputType(InputType.TYPE_CLASS_NUMBER);

        init();
    }

    @Override
    protected void onResume() {
        super.onResume();
        HttpHelper.inst().submitEvent("LOGIN","START","");
    }

    @Override
    protected void onPause() {
        super.onPause();
        HttpHelper.inst().submitEvent("LOGIN","END","");
    }

    private void init(){

        csImageButton.setOnClickListener(v -> new CusServiceAkomapalendDialog(this).show());

        String areaCode = AkomapaLendUtil.mobileCode();
        mobileCodeTextView.setText(areaCode);
        AkomapaLendUtil.mobileCode(areaCode);

        requestCodeButton.setOnClickListener(requestCodeC);
        loginButton.setOnClickListener(loginC);

        agreementImageButton.setOnClickListener(v -> {
            HttpHelper.inst().submitEvent("LOGIN","STATEMENT_CHECK_CLICK",!flag ? "YES":"NO");
            setFlag(!flag);
        });
        agreementTextView.setOnClickListener(v -> {
            HttpHelper.inst().submitEvent("LOGIN","STATEMENT_CLICK","");
            String agreementUrl = AppAkomapalendConfigCustomize.instance().getAgreementUrl_akomapalend();
            if (TextUtils.isEmpty(agreementUrl)) return;
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(agreementUrl)));
        });

        mobileCodeInputEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 4){

                    String mobile = mobileInputEditText.getText().toString().trim();
                    String vercode = mobileCodeInputEditText.getText().toString().trim();

                    HttpHelper.inst().submitEvent("LOGIN","OTP_DONE",vercode);

                    if (TextUtils.isEmpty(mobile)) return;

                    //测试账号自动登录
                    if (AppAkomapalendConfigCustomize.instance().isTestAccount_akomapalend(mobile)){
                        try {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("token", AppAkomapalendConfigCustomize.instance().getTestToken_akomapalend(mobile));
                            jsonObject.put("userId", mobile);
                            jsonObject.put("type", AkomapaLendConfigs.LoginTypeOld);
                            jsonObject.put("isAdSource","NO");
                            LogAkomapalendinInfo.par_akomapalendse(jsonObject);
                            loginSuccess();
                        }catch (JSONException e){
                            e.printStackTrace();
                        }
                        return;
                    }

                    HttpHelper.inst().lgWCode(LoginActivity.this,mobile,vercode,() -> loginSuccess());

                }
            }
        });

        mobileInputEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {

                String mobile = mobileInputEditText.getText().toString();
                String vercode = mobileCodeInputEditText.getText().toString();

                if (TextUtils.isEmpty(mobile) || TextUtils.isEmpty(vercode)){
                    loginButton.setBackgroundResource(R.drawable.back_purple_round_c_white);
                    loginImageView.setBackgroundResource(R.drawable.icon_next_white);
                }else {
                    loginButton.setBackgroundResource(R.drawable.back_3_color_gradient);
                    loginImageView.setBackgroundResource(R.drawable.icon_refresh_white);
                }

            }
        });

        mobileCodeInputEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {

                String mobile = mobileInputEditText.getText().toString();
                String vercode = mobileCodeInputEditText.getText().toString();

                if (TextUtils.isEmpty(mobile) || TextUtils.isEmpty(vercode)){
                    loginButton.setBackgroundResource(R.drawable.back_purple_round_c_white);
                    loginImageView.setBackgroundResource(R.drawable.icon_next_white);
                }else {
                    loginButton.setBackgroundResource(R.drawable.back_3_color_gradient);
                    loginImageView.setBackgroundResource(R.drawable.icon_refresh_white);
                }

            }
        });

    }

    private void setFlag(boolean flag) {
        this.flag = flag;
        agreementImageButton.setBackgroundResource(flag ? R.drawable.icon_check9 :R.drawable.icon_no_check_2);
    }

    @SuppressLint("SetTextI18n")
    public void requestCodeSuccess(){

        Toast.makeText(this,getString(R.string.tips_vercode_send_success_akomapalend),Toast.LENGTH_SHORT).show();
        requestCodeButton.setOnClickListener(null);
        requestCodeButton.setBackgroundResource(R.drawable.back_purple_white);

        String mobile = mobileInputEditText.getText().toString().trim();
        JSONObject jsonObject = OtheAkomapalendrsInfo.instance().getSendOtpCodeJson_akomapalend();
        if (jsonObject!=null){
            String directLogin = jsonObject.optString("directLoginFlag");
            if (directLogin.equalsIgnoreCase("YES")) {
                HttpHelper.inst().oldUserLg(this,mobile,this::loginSuccess);
                return;
            }
        }

        new Thread(() -> {

            int count = 60;

            while (count-- > 0){
                final int finalCount = count;
                runOnUiThread(() -> requestCodeButton.setText(finalCount+"s"));
                try {
                    Thread.sleep(999);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

            runOnUiThread(() -> {
                requestCodeButton.setOnClickListener(requestCodeC);
                requestCodeButton.setText(getString(R.string.login_get_code));
                requestCodeButton.setBackgroundResource(R.drawable.back_blue_purple);
            });

        }).start();

    }

    public void loginSuccess(){

        AkomapaLendUtil.sMobile(mobileInputEditText.getText().toString());
        AkomapaLendUtil.sToken(LogAkomapalendinInfo.getIns_akomapalendtance().getT_akomapalendoken());
        AkomapaLendUtil.sUserId(LogAkomapalendinInfo.getIns_akomapalendtance().getUse_akomapalendrId());
        AkomapaLendUtil.sIsAdSource(LogAkomapalendinInfo.getIns_akomapalendtance().getIs_akomapalendAdSource());

        if (LogAkomapalendinInfo.getIns_akomapalendtance().getT_akomapalendype().equalsIgnoreCase(AkomapaLendConfigs.LoginTypeRegister))
            AkomapalendAnalyticsUtil.INSTANCE.addEvent(AkomapalendIAnalyticsEvent.AT_REGISTER);

        HttpHelper.inst().process(this,this::handleProcess);

    }

    public void handleProcess(){
        startActivity(new Intent(this, HomeActivity.class));
        finish();
    }

}